package Ejercicio3;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;


public class ServidorChat implements Servidor {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ArrayList<Cliente> clientes;
	private long numMensaje; 
	
	public ServidorChat() {
		clientes = new ArrayList<Cliente>();
		numMensaje = 0;
	}
	@Override
	public synchronized void difundir(String mensaje) throws RemoteException {
		numMensaje++;
		for (Cliente c : clientes) {
			c.recibir(numMensaje + ": " + mensaje);
		}
	}

	private int contador = 1;
	@Override
	public int inscribirse(Cliente c) throws RemoteException {
		clientes.add(c);
		return contador++;
	}

	public static void main(String[] main) {
        try {
        	ServidorChat obj = new ServidorChat();
        	Servidor stub = (Servidor) UnicastRemoteObject.exportObject(obj, 0);

            // Bind the remote object's stub in the registry
            Registry registry = LocateRegistry.getRegistry();
            try {
	            registry.unbind("Servidor");
	        }catch (NotBoundException e) {
	        	
	        }
            registry.bind("Servidor", stub);

            System.err.println("Server ready");
        } catch (Exception e) {
            System.err.println("Server exception: " + e.toString());
            e.printStackTrace();
        }
	}

}
